from datetime import datetime, date
from decimal import Decimal
from enum import Enum

from sqlalchemy import Column, Integer, String, Date, DECIMAL, DateTime, func, ForeignKey, Enum as SQLEnum
from sqlalchemy.orm import relationship
from backend.db.base import Base
from backend.models.member_transaction import Transaction


class Member(Base):
    __tablename__ = 'member'

    id = Column(Integer, primary_key=True, nullable=False, comment='会员id')
    member_code = Column(String(20), unique=True, index=True, nullable=False, comment='会员编号')
    name = Column(String(10), nullable=False, index=True, comment='姓名')
    phone = Column(String(20), nullable=False, index=True, comment='手机号')
    registration_date = Column(Date, default=date.today(), nullable=False, comment='登记日期')
    initial_balance = Column(DECIMAL(10, 2), default=0.00, nullable=False, comment='初始余额')
    current_balance = Column(DECIMAL(10, 2), default=0.00, nullable=False, comment='当前余额')
    total_consumption = Column(DECIMAL(10, 2), default=0.00, nullable=False, comment='总消费金额')
    consumption_count = Column(Integer, default=0, nullable=False, comment="消费次数")
    last_consumption_date = Column(DateTime, comment='最后消费日期')
    note = Column(String(100), comment='备注')
    created_at = Column(DateTime, default=func.now(), nullable=False, comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False, comment="更新时间")

    transactions = relationship('Transaction', backref='member', cascade='all,delete-orphan', lazy="select")
    member_certificates = relationship('MemberCertificate', backref='member', cascade='all,delete-orphan',
                                       lazy="select")

    def __repr__(self):
        return f"<会员(id={self.id}, 会员编号='{self.member_code}', 姓名='{self.name}')>"

    @property
    def balance_status(self):
        """获取余额状态"""
        if self.current_balance <= 0:
            return '余额不足'
        elif self.current_balance < 100:
            return '余额较低'
        else:
            return '余额充足'


class CertificatesStatus(str, Enum):
    YES = "已消费"
    NO = "待消费"


class MemberCertificate(Base):
    __tablename__ = 'member_certificate'

    id = Column(Integer, primary_key=True, nullable=False, comment='存单id')
    member_id = Column(Integer, ForeignKey('member.id'), nullable=True, comment='会员id')
    certificates = Column(String(20), default="无", nullable=False, comment='存单内容')
    certificates_status = Column(SQLEnum(CertificatesStatus), default=CertificatesStatus.NO, nullable=False)
    created_at = Column(DateTime, default=func.now(), nullable=False, comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), nullable=False, comment="更新时间")

    @property
    def zh_cn_display(self):
        """获取交易类型中文显示"""
        type_map = {
            CertificatesStatus.YES: "已消费",
            CertificatesStatus.NO: "待消费"
        }
        return type_map.get(self.certificates_status, "未知")
